package com.jiangyg.mall.order.listener;

import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.order.dto.OrderReleaseDTO;
import com.jiangyg.mall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 类描述：订单释放队列监听
 * <p>消息来源：</p>
 * <p>1、在队列 order.delay.queue 中超过30分钟的订单，会自动通过死信交换机到此队列。</p>
 * <p>2、会员主动触发订单取消。</p>
 *
 * @author jiangyg
 * @date 2022-12-18
 */
@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "order.release.queue", autoDelete = "false"),
        exchange = @Exchange(value = "order-event-exchange", type = ExchangeTypes.TOPIC)
))
public class OrderReleaseQueueListener {

    private final OrderService orderService;

    @Autowired
    public OrderReleaseQueueListener(OrderService orderService) {
        this.orderService = orderService;
    }

    @RabbitHandler
    public void listener(OrderReleaseDTO dto, Channel channel, Message message) throws IOException {
        try {
            Logger.info(log, () -> String.format("[订单释放监听]-监听到订单[%d]已到过期时间，进行释放处理……", dto.getId()));
            this.orderService.release(dto, null);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ex) {
            Logger.info(log, () -> String.format("[订单释放监听]-订单[%d]释放处理出错……", dto.getId()), ex);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
